package com.fgchen.biz;

import com.fgchen.util.excel.ExcelConfig;
import com.fgchen.util.excel.ExcelUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Collection;

/**
 * Created by Administrator on 2018-04-09.
 */
@Component
public class ExcelBiz {

    public <T> InputStream generateExcel(Collection<T> coll, ExcelConfig excelConfig) throws Exception {
        Workbook workbook = ExcelUtil.getWorkbook(excelConfig);
        Sheet sheet = workbook.getSheet(excelConfig.getSheetName());
        int start = excelConfig.getStartRow();
        for (T item : coll) {
            Row row = sheet.createRow(start);
            ExcelUtil.generateRow(item, row, excelConfig);
            start++;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        workbook.write(baos);
        workbook.close();
        baos.close();

        return new ByteArrayInputStream(baos.toByteArray());
    }

}
